import config from "../config/index.js";
import qs from 'qs'
// import { JSEncrypt } from './jsencrypt.js';
import store from "@/store";
// var RSA = require('./wx_rsa.js')
import {
	ParamsToFormData
} from "./util.js";

function getCommonHeader(url) {
	let header = {
		'Content-type': 'application/x-www-form-urlencoded',
	};
	return header;
};


function rasRoute(url) {
	// console.log(JSEncrypt);
	const timeStamp = Number(new Date());
	const publicKey =
		"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCZ1si7+z7yhfb+OxtCaR8VNNX8JyKL3FzAztA3FLYKyKS1R3+t6Pn/5+obFANI3irJ6qWFReazzr6DvsJDLTu/e5DuWbJsrmPMUaXwngGBSUutWNJjZMdr7fDleSPQGQNfKZGbMHyg98fKZJx/L3zVAQuWcfgNEHjjk9XDrlfrrwIDAQAB0";
	const str = "/" + url + "@" + timeStamp;
	var encrypt_rsa = new RSA.RSAKey();
	encrypt_rsa = RSA.KEYUTIL.getKey(publicKey);
	console.log('加密RSA:')
	console.log(encrypt_rsa)
	encStr = encrypt_rsa.encrypt(input_rsa)
	encStr = RSA.hex2b64(encStr);
	console.log("加密结果：" + encStr)

	// const jse = new JSEncrypt();
	// //设置公钥
	// jse.setPublicKey(publicKey);
	// const str = "/" + url + "@" + timeStamp;
	// console.log(jse.encrypt(str), str, publicKey);
	// return jse.encrypt(str);
}

/**
 * 删除为空参数
 */
function deleteEmpty(data) {
	const keys = Object.keys(data);
	if (keys) {
		keys.filter(val => {
			if (data[val] == null || data[val] == undefined) delete data[val];
		})
	}
	return data;
};

/**
 * 网络请求
 */
function $http(url, data = {}, header = {}, method = "GET") {
	if (data && data != {}) {
		// post请求序列化参数
		data = deleteEmpty(data);
		if (method == "POST" && header['Content-type'] != 'application/json') {
			data = qs.stringify(data);
		}
		// console.log('参数', data);
	}
	// header 空值处理
	let _header = getCommonHeader(url);
	if (Object.keys(header).length > 0) {
		_header = {
			...header
		};

	}
	// 如果token有值则带上
	// let token = uni.getStorageSync("token");
	// let tokenHead = uni.getStorageSync("tokenHead");

	// _header = Object.assign({}, _header, {
	// 	'Authorization': rasRoute(url)
	// });

	const isShowLoading = true;
	let isLoading = false;
	return new Promise((resolve, reject) => {
		// 是否显示loading
		if (isShowLoading) {
			uni.showLoading({
				title: "加载中",
				mask: true
			});
			isLoading = true;
		}
		uni.request({
			url: config.baseurl + url,
			data: data,
			header: _header,
			method: method,
			dataType: "json",
			// #ifdef H5
			withCredentials: true,
			// #endif
			success: (res => {
				if (isLoading && isShowLoading) {
					uni.hideLoading();
					isLoading = false;
				}
				// 服务器 非200 错误
				if (res.statusCode && res.statusCode != 200) {
					if (res.statusCode == 401) {
						uni.removeStorageSync('sys_userInfo')
						if (!isLoading) {
							uni.showToast({
								title: "登录过期，自动重连中！",
								icon: 'none'
							});
						}
						// uni.redirectTo({
						// 	url: '/pages/login/login'
						// });
					} else {
						if (!isLoading) {
							uni.showToast({
								title: '服务器 ' + res.statusCode + ' 错误',
								icon: 'none'
							});
						}
					}
					return reject(res);
				}

				if (res.data && res.data.code != 0) {
					// 业务状态非0 是否提示
					// if(res.data.code !== 208){
					//   if(!isLoading){
					//     uni.showToast({ title: res.data.msg, icon: 'none' });
					//   }
					// }
					return reject(res.data);
				}
				resolve(res.data);
			}),
			fail: (err => {
				if (isLoading && isShowLoading) {
					uni.hideLoading();
					isLoading = false;
				}
				if (err.errMsg.indexOf('url not in domain list') > -1) {
					if (!isLoading) {
						uni.showToast({
							title: '请求url不在合法域名中',
							icon: 'none'
						});
					}
				}
				reject(err);
			})
		});
	});
};

/**
 * 文件上传
 */
function uploadFile(url, data = {}, avatarName = "photo", fileType = "image", header = {}) {
	const isShowLoading = true;
	let isLoading = false;
	if (data.params) {
		data.params = qs.stringify(data.params);
		data.params = qs.parse(data.params);
		console.log("data---", data.file.path, data.params)
	} else {
		data.params = {};
	}
	return new Promise((resolve, reject) => {
		// 是否显示loading
		if (isShowLoading) {
			uni.showLoading({
				title: "加载中",
				mask: true
			});
			isLoading = true;
		}
		uni.uploadFile({
			url: config.baseurl + url, //仅为示例，非真实的接口地址
			filePath: data.file.path,
			fileType: fileType,
			name: avatarName,
			formData: data.params,
			success: (res) => {
				if (isLoading && isShowLoading) {
					uni.hideLoading();
					isLoading = false;
				}
				if (res.statusCode == 200) {
					res.data = JSON.parse(res.data);
					if (res.data && res.data.code != 0) {
						return reject(res.data);
					} else {
						resolve(res.data);
					}
				}
				return reject(res.data);
			},
			fail: (err => {
				if (isLoading && isShowLoading) {
					uni.hideLoading();
					isLoading = false;
				}
				if (err.errMsg.indexOf('url not in domain list') > -1) {
					if (!isLoading) {
						uni.showToast({
							title: '请求url不在合法域名中',
							icon: 'none'
						});
					}
				}
				reject(err);
			})
		});
	});
}

module.exports = {
	/**
	 * get 网络请求
	 */
	get(url, data = {}, header = {}) {
		return $http(url, data, header, "GET");
	},

	/**
	 * post 网络请求
	 */
	post(url, data = {}, header = {}) {
		return $http(url, data, header, "POST");
	},

	/**
	 * put 网络请求
	 */
	put(url, data = {}, header = {}) {
		return $http(url, data, header, "PUT");
	},

	/**
	 * put 网络请求
	 */
	delete(url, data = {}, header = {}) {
		return $http(url, data, header, "DELETE");
	},

	/**
	 * upload文件上传
	 */
	upload(url, data = {}, avatarName = "photo", fileType = "image", header = {}) {
		return uploadFile(url, data, avatarName, fileType, header = {});
	},
}